package com.sinven.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sinven.mapper.MenuMapper;
import com.sinven.pojo.Menu;

@Service
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuMapper menuMapper;

	@Override
	public List<Menu> queryMenuList() {
		// 原始数据
		List<Menu> rootMenu = menuMapper.queryMenus();
		
		//构建有层级的Menu
		List<Menu> menuList = new ArrayList<Menu>();
		
		//取出所有顶级菜单
		for (Menu menu : rootMenu) {
			if(menu.getPid() == 0) {
				menuList.add(menu);
			}
		}
		
		//设置子菜单
		for (Menu menu : menuList) {
			menu.setChildren(getChild(menu.getId(),rootMenu));
		}
		return menuList;
	}

	private List<Menu> getChild(Long id, List<Menu> rootMenu) {
		// 子菜单
	    List<Menu> childList = new ArrayList<>();
		for (Menu menu : rootMenu) {
			if (menu.getPid() == id) {
				childList.add(menu);
			}
		}
		 // 把子菜单的子菜单再循环一遍
	    for (Menu menu : childList) {// 没有url子菜单还有子菜单
	            // 递归
	       menu.setChildren(getChild(menu.getId(), rootMenu));
	    } // 递归退出条件
	    if (childList.size() == 0) {
	        return null;
	    }
	    return childList;
	}

}
